#Function 1: loads packages and installs if not already installed
package_load <- function(package_vector){
  #Collects a list of packages not installed
  not_installed <- package_vector[!(package_vector %in% installed.packages()[,"Package"])]
  
  #install if not already installed
  if(length(not_installed) > 0){
    for(i in 1:length(not_installed)){
      install.packages(not_installed[i], dependencies = TRUE)
    }}
  
  #load packages
  for(i in 1:length(package_vector)){
    require(package_vector[i], character.only = TRUE)}
  }


#Function 2: loads standard packages
load_standard <- function(){
  to_load <- c("cluster","doBy","dplyr","foreign","ggplot2","ggthemes",
               "Hmisc","knitr","lmtest", "multiwayvcov","ordinal",
               "pastecs", "plm", "plyr", "readstata13","reshape2",
               "stargazer","tibble","xtable")
  forward = FALSE
while(forward == FALSE){
  cat("Currently will load: ", paste(to_load, sep = " "))
  add_remove <- readline("Do you want to add or remove any functions? 'y' for yes, 'n' for no ")
  if(add_remove == "y"){forward = FALSE} else{forward = TRUE}
  if(forward == FALSE)
    {to_add <- readline("List functions to add: ")
    to_add <- unlist(strsplit(to_add, "[, ]+"))
    to_remove <- readline("List functions to remove: ")
    to_remove <- unlist(strsplit(to_remove, "[, ]+"))
    to_load <-   subset(to_load, !(to_load %in% to_remove))
    to_load <- c(to_load, to_add)}
}
  package_load(to_load)
}

#Function 3: Significance test (correlation plots)
#See https://cran.r-project.org/web/packages/corrplot/vignettes/corrplot-intro.html
cor.mtest <- function(mat, conf.level = 0.95){
  mat <- as.matrix(mat)
  n <- ncol(mat)
  p.mat <- lowCI.mat <- uppCI.mat <- matrix(NA, n, n)
  diag(p.mat) <- 0
  diag(lowCI.mat) <- diag(uppCI.mat) <- 1
  for(i in 1:(n-1)){
    for(j in (i+1):n){
      tmp <- cor.test(mat[,i], mat[,j], conf.level = conf.level)
      p.mat[i,j] <- p.mat[j,i] <- tmp$p.value
      lowCI.mat[i,j] <- lowCI.mat[j,i] <- tmp$conf.int[1]
      uppCI.mat[i,j] <- uppCI.mat[j,i] <- tmp$conf.int[2]
    }
  }
  return(list(p.mat, lowCI.mat, uppCI.mat))
}
